package team.bluepen.order.web.servlet;

import team.bluepen.order.ErrorPack;
import team.bluepen.order.constant.Constant;
import team.bluepen.order.constant.ErrorCode;
import team.bluepen.order.data.hdfs.HdfsManager;
import team.bluepen.order.util.Log;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 文件上传
 * @author Kai
 */
@WebServlet(name = "FileUploadServlet", urlPatterns = "/api/file/upload")
@MultipartConfig(maxFileSize = Constant.FILE_MAX_SIZE)
public class FileUploadServlet extends BaseServlet {
    private static final String TAG = "FileUploadServlet";
    public static final String FILE_PARAM = "file_upload";
    public static final String TEMP_DIRECTORY = Constant.TEMP_DIRECTORY;

    @Override
    protected void post(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        setJsonHeader(resp);
        Part part = req.getPart(FILE_PARAM);
        String fileName = part.getSubmittedFileName();
        Log.i(TAG, "start upload. File name:" + fileName);
        InputStream stream = part.getInputStream();
        if (stream.available() > Constant.FILE_MAX_SIZE) {
            writeJson(resp, new ErrorPack(ErrorCode.ERROR_FILE_OVERSIZE,
                    "File oversize.").toCodePack());
            return;
        }

        String suffix = getFileNameSuffix(fileName);
        if (!suffix.equalsIgnoreCase("csv")
                && !suffix.equalsIgnoreCase("txt")) {
            writeJson(resp, new ErrorPack(ErrorCode.ERROR_FILE_UNMATCHED,
                    "An unsupported suffix type.").toCodePack());
            return;
        }

        String dateSuffix = getDateFormat();
        File outputFileDirectory = new File(TEMP_DIRECTORY);
        boolean dirState = outputFileDirectory.mkdirs();// 创建文件夹

        File file = new File(TEMP_DIRECTORY + "/" + fileName);

        if (!file.exists()) {
            boolean createState = file.createNewFile();
        }

        FileOutputStream outputStream = new FileOutputStream(file);

        int len;
        byte[] bytes = new byte[1024];
        while ((len = stream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, len);
        }

        HdfsManager.getInstance().mkdirs(Constant.UPLOAD_DIRECTORY);
        String path = Constant.UPLOAD_DIRECTORY + "/" + dateSuffix + "/" + fileName;
        ErrorCode uploadState = HdfsManager.getInstance().upload(
                file.getAbsolutePath(), path);
        boolean deleteState = file.delete();

        stream.close();
        outputStream.close();

        if (!uploadState.getState()) {
            writeJson(resp, new ErrorPack(ErrorCode.ERROR_FILE_UPLOAD,
                    "An error occurred when uploading file.").toCodePack());
            return;
        }
        Log.i(TAG, "upload success. path = " + path);
        writeJson(resp, new ErrorPack(ErrorCode.SUCCESS,
                "SUCCESS").toCodePack());
    }

    /**
     * 由文件名获取后缀名
     * @param path 路径
     * @return 后缀名
     * */
    private static String getFileNameSuffix(String path){
        if (path == null) {
            return null;
        }
        int start = path.lastIndexOf(".");
        if (start != -1) {
            return path.substring(start + 1);
        } else {
            return "";
        }
    }

    private static String getDateFormat() {
       return getDateFormat(System.currentTimeMillis());
    }

    private static String getDateFormat(long timestamp) {
        Date date = new Date(timestamp);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM");
        return dateFormat.format(date);
    }
}
